<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form class="permission-form" :form="form">
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="唯一标识" v-show="xsFlag" hasFeedback>
        <a-input v-decorator="['id']" :disabled="true" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="电话名称" hasFeedback>
        <a-input
          placeholder="输入电话"
          autocomplete="phone"
          v-decorator="['phone', { rules: [{ required: true, message: '电话不能为空' }] }]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" hasFeedback>
        <a-input
          placeholder="输入密码"
          autocomplete="password"
          v-decorator="['password', { rules: [{ required: true, message: '密码' }] }]"
        />
      </a-form-item>
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务简介" hasFeedback>
        <a-textarea
          placeholder="请输入服务简介"
          autocomplete="remark"
          v-decorator="['remark', { rules: [{ required: true, message: '服务简介不能为空' }] }]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务价格" hasFeedback>
        <a-input-number
          autocomplete="price"
          v-decorator="['price', { rules: [{ required: true, message: '价格不能为空' }] }]"
        />
        <a-button @click="tjprice" style="margin-left: 400px">添加价格</a-button>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="价格" hasFeedback>
        <a-tag closable v-for="item in prices" :key="item" @close="() => handleCloses2(item)">{{ item }}</a-tag>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格" hasFeedback>
        <a-input placeholder="起一个规格" autocomplete="specification" v-decorator="['specification']" />
        <a-button @click="tjguige" style="margin-left: 400px">添加规格</a-button>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格" hasFeedback>
        <a-tag closable v-for="item in guige" :key="item" @close="() => handleCloses(item)">{{ item }}</a-tag>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务轮播图" hasFeedback>
        <a-upload
          :customRequest="uploadimage"
          list-type="picture-card"
          :file-list="fileList"
          @preview="handlePreview"
          @change="handleChange"
          :remove="removeFile"
          :beforeUpload="beforeUpload"
          multiple
        >
          <div v-if="fileList.length < 6">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleC">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务详情" hasFeedback>
        <a-upload
          :customRequest="uploadimage2"
          list-type="picture-card"
          :file-list="fileList2"
          @preview="handlePreview"
          :remove="removeFile2"
          :beforeUpload="beforeUpload2"
          multiple
        >
          <div v-if="fileList2.length < 6">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleC">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script>
import { decryptStr } from '@/utils/passwordUtils'

// import { decryptStr } from '@/utils/passwordUtils'
// import { getPermissions } from '@/api/manage'
// import pick from 'lodash.pick'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'RoleModal',
  data() {
    return {
      guige: [],
      imgflag: true,
      typed: 1,
      RolesLists: [],
      xsFlag: false,
      title: '新增角色',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      // mdl: {
      //   actions: [] // 初始化为默认选中的值
      // },

      form: this.$form.createForm(this),
      permissions: [],
      previewVisible: false,
      previewImage: '',

      fileList2: [],
      fileList: [
        /* {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-2',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-3',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-4',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-5',
          name: 'image.png',
          status: 'error'
        } */
      ],
      prices: []
    }
  },
  created() {
    // this.loadPermissions()
  },
  mounted() {
    // console.log('mounted')
  },
  methods: {
    handleCloses(removedTag) {
      const tags = this.guige.filter((tag) => tag !== removedTag)
      console.log(tags)
      this.guige = tags
    },
    handleCloses2(removedTag) {
      const tags = this.prices.filter((tag) => tag !== removedTag)
      console.log(tags)
      this.prices = tags
    },
    tjprice() {
      const specification = this.form.getFieldValue('price')
      console.log('价格', specification)

      // 检查数组中是否已经存在传入的值
      if (this.prices.includes(specification)) {
        // 如果存在，给出提示
        this.$notification['error']({
          message: '此价格已经添加',
          description: '请重新添加',
          duration: 2
        })
      } else {
        // 如果不存在，添加到数组
        this.prices.push(specification)
      }
    },
    tjguige() {
      const specification = this.form.getFieldValue('specification')
      console.log('guig', specification)

      // 检查数组中是否已经存在传入的值
      if (this.guige.includes(specification)) {
        // 如果存在，给出提示
        this.$notification['error']({
          message: '此规格已经添加',
          description: '请重新添加',
          duration: 2
        })
      } else {
        // 如果不存在，添加到数组
        this.guige.push(specification)
      }
    },
    beforeUpload(file, fileLists) {
      // console.log('file', file)
      // console.log('fileList', fileList)
      // if (this.fileList.length + fileList.length > 6) {
      //   this.imgflag = true
      //   if (this.imgflag) {
      //     this.$notification['error']({
      //       message: '最多上传六张图片',
      //       description: '请重新添加',
      //       duration: 2
      //     })
      //   }
      //   setTimeout(() => {
      //     this.imgflag = false
      //   }, 2000)
      //   return false
      // }
      // return true
      if (this.fileList.length + fileLists.length > 6) {
        if (this.imgflag) {
          this.$message.success('轮播图最多只能选6张')
          this.imgflag = false
        }
        setTimeout(() => {
          this.imgflag = true
        }, 2000)
        return false
      } else {
        return true
      }
    },
    beforeUpload2(file, fileLists2) {
      // console.log('file', file)
      // console.log('fileList', fileList)
      // if (this.fileList.length + fileList.length > 6) {
      //   this.imgflag = true
      //   if (this.imgflag) {
      //     this.$notification['error']({
      //       message: '最多上传六张图片',
      //       description: '请重新添加',
      //       duration: 2
      //     })
      //   }
      //   setTimeout(() => {
      //     this.imgflag = false
      //   }, 2000)
      //   return false
      // }
      // return true
      if (this.fileList2.length + fileLists2.length > 6) {
        if (this.imgflag) {
          this.$message.success('轮播图最多只能选6张')
          this.imgflag = false
        }
        setTimeout(() => {
          this.imgflag = true
        }, 2000)
        return false
      } else {
        return true
      }
    },
    gbChange(e) {
      console.log('改变', e)
      this.typed = e
    },
    filterOption(input, option) {
      // console.log('input', input)
      // console.log('option', option)

      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    removeFile(file) {
      // console.log('删除文件', e.name)
      // this.$http.post('/common/del', { filename: e.name }).then((res) => {
      //   console.log(res)
      // })
      // this.fileList = []
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    removeFile2(file) {
      // console.log('删除文件', e.name)
      // this.$http.post('/common/del', { filename: e.name }).then((res) => {
      //   console.log(res)
      // })
      // this.fileList2 = []
      const index = this.fileList2.indexOf(file)
      const newFileList = this.fileList2.slice()
      newFileList.splice(index, 1)
      this.fileList2 = newFileList
    },
    uploadimage(file, fileList) {
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file) // 'file' 是文件的表单字段名，file 是文件对象
      this.$http
        .post('/serviceClassification/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 确保请求头设置为 multipart/form-data
          }
        })
        .then((res) => {
          console.log('上传成功', res.result[0])

          this.fileList.push(res.result[0])
          console.log('图片', this.fileList)
        })
    },
    uploadimage2(file, fileList) {
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file) // 'file' 是文件的表单字段名，file 是文件对象
      this.$http
        .post('/serviceClassification/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 确保请求头设置为 multipart/form-data
          }
        })
        .then((res) => {
          console.log('上传成功', res.result[0])

          this.fileList2.push(res.result[0])
          console.log('图片', this.fileList2)
        })
    },
    handleC() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      // this.fileList = fileList
    },
    filterByValue(arr, valueArray) {
      return arr.filter((item) => valueArray.includes(item.value))
    },
    // 验证状态的动态显示
    validateStatus(fieldName) {
      const { getFieldError, isFieldTouched } = this.form
      if (isFieldTouched(fieldName) && getFieldError(fieldName)) {
        return 'error'
      }
      return 'success'
    },
    add() {
      console.log('add')

      this.visible = true
      this.xsFlag = false
      this.title = '新增服务'
      this.fileList = []
      this.fileList2 = []
      this.guige = []
      this.prices = []
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue({
            id: '',
            phone: '',
            password: ''
          })
        })
      })

      // this.loadPermissions()
    },
    watch(record) {
      console.log('watch', record)
      this.title = '查看角色'
    },
    returnvalue(arr) {
      return arr.map((item) => {
        return item.value
      })
    },
    edit(record) {
      this.mdl = Object.assign({}, record)
      this.visible = true
      console.log('数据', this.mdl)
      this.title = '编辑服务'
      this.xsFlag = true
      this.typed = record.type
      // if (record.flImage) {
      //   this.fileList = []
      //   this.fileList.push(JSON.parse(record.flImage))
      // } else {
      //   this.fileList = []
      // }
      this.fileList = this.mdl.serviceCarousel
      this.fileList2 = this.mdl.serviceDetails
      this.guige = this.mdl.specification
      this.prices = this.mdl.price
      this.$nextTick(() => {
        // this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'code', 'status'))
        this.form.setFieldsValue({
          // id: this.mdl.id,
          // code: this.mdl.name,
          // status: this.mdl.status,
          // name: this.mdl.code,
          id: this.mdl.id,

          phone: this.mdl.phone,
          password: decryptStr(this.mdl.slat, this.mdl.password)
        })
      })
      // console.log('this.mdl', this.mdl)
    },
    close() {
      // this.$emit('close')

      this.visible = false
    },
    handleOk() {
      // // 触发表单验证
      console.log('出发')
      // if (this.prices.length !== this.guige.length) {
      //   this.$message.error('价格和规格数量不一致')
      //   return
      // }
      this.form.validateFields((err, values) => {
        console.log('err', err)

        // 验证表单没错误
        if (!err) {
          console.log('form values', values)
          // const aa = this.filterByValue(this.RolesLists, values.roles)
          // console.log('j橘角色', aa)
          if (values.id > 0) {
            const tabledate = this.$removeSpacesFromObject(values)
            // console.log('修改头像', this.fileList)
            // console.log('用户的相关信息', tabledate)

            this.$http
              .put('/employees/htupdate', {
                id: tabledate.id,

                phone: tabledate.phone,
                password: tabledate.password
              })
              .then((res) => {
                console.log('res', res)
                if (res.code === 200) {
                  this.$message.success('修改成功')
                  this.$emit('ok')
                }
              })
          } else {
            const tabledate = this.$removeSpacesFromObject(values)
            console.log('添加头像', this.fileList)
            console.log('添加头像2', this.fileList2)
            console.log('guige', this.guige)

            console.log('用户的相关信息', tabledate)
            this.$http
              .post('/employees/htinsert', {
                id: tabledate.id,

                phone: tabledate.phone,
                password: tabledate.password
              })
              .then((res) => {
                console.log('res', res)
                if (res.code === 200) {
                  this.$message.success('添加成功')
                  this.$emit('ok')
                } else {
                  this.$message.error(res.message)
                }
              })
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChangeCheck(permission) {
      permission.indeterminate =
        !!permission.selected.length && permission.selected.length < permission.actionsOptions.length
      permission.checkedAll = permission.selected.length === permission.actionsOptions.length
    },
    onChangeCheckAll(e, permission) {
      Object.assign(permission, {
        selected: e.target.checked ? permission.actionsOptions.map((obj) => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    del(e) {
      console.log('删除', e)
    },
    disable() {},
    loadPermissions() {
      // const that = this
      // console.log(that)
      this.$http
        .get('/servicedetails/serviceParent')
        .then((res) => {
          // console.log('下拉权限', res)
          if (res.code === 200) {
            this.RolesLists = res.result
            // console.log('数据', this.RolesLists)
          }
        })
        .catch((err) => {
          console.log('出错', err)
        })
    }
  }
}
</script>

<style scoped></style>
